<script lang="ts">
export default { name: 'ChannelForm' }
</script>

<script setup lang="ts">
import { ref, computed, toRefs, watch } from 'vue'
import { toTree, disableSubtree } from '@/utils/cmstree'
import { getChannelTpl } from '@/api/cms/tpl'
import { getModelSimpleListApi } from '@/api/bpm/model'
import { getModelList } from '@/api/cms/model/index'
import FieldItem from '@/views/cms/setting/cmsmodel/component/FieldItem.vue'
import LabelTip from '@/components/cms/LabelTip.vue'
import DialogForm from '@/components/cms/DialogForm.vue'
import * as ChannelApi from '@/api/cms/channel'
import { arr2obj, getModelData, mergeModelFields } from '@/utils/cmscommon'
const { t } = useI18n() // 国际化
const props = defineProps({
  modelValue: { type: Boolean, required: true },
  channelId: { type: Number, default: null },
  parent: { type: Object, default: null }
})
const emit = defineEmits({
  'update:modelValue': null,
  'update:values': null,
  finished: null,
  beanChange: null,
  beforeSubmit: null
})
const { modelValue: visible, parent,channelId } = toRefs(props)
const focus = ref<any>()
const values = ref<any>({})
const channelList = ref<any[]>([])
const channelModelList = ref<any[]>([])
const modelId = ref<number>()
const contentModelList = ref<any[]>([])
const contentModelId = ref<number>()
const channelPcTemplates = ref<any[]>([])
const contentPcTemplates = ref<any[]>([])
const channelH5Templates = ref<any[]>([])
const contentH5Templates = ref<any[]>([])
const processDefinitions = ref<any[]>([])
const channelModel = computed(() =>
  channelModelList.value.find((item) => item.id === modelId.value)
)
const fetchChannelList = async () => {
  channelList.value = toTree(await ChannelApi.getChannelListApi())
}
const finished = async () => {
  await fetchChannelList()
  emit('finished')
}
//主面板左边字段
const mainFields = computed(() => {
  const cus = arr2obj(
    mergeModelFields(getModelData().channel.mainFields, channelModel.value?.mainFields, 'channel')
  )
  return cus
})
//主面板右侧字段
const rightFields = computed(() =>
  arr2obj(
    mergeModelFields(getModelData().channel.rightFields, channelModel.value?.rightFields, 'channel')
  )
)
//自定义字段
const fields = computed(() => JSON.parse(channelModel.value?.customs || '[]'))
const parentChannelList = computed(() => {
  const list = disableSubtree(channelList.value, values.value.id)
  //TODO 用户权限范围的栏目
  return list
})
const fetchChannelModelList = async () => {
  channelModelList.value = await getModelList(1)
  // 如果 modelId 无值，则默认赋予第一个模型的值
  if (modelId.value == null && channelModelList.value.length > 0) {
    modelId.value = channelModelList.value[0].id
  }
}
const fetchContentModelList = async () => {
  contentModelList.value = await getModelList(2)
}
const fetchChannelPcTemplates = async () => {
  channelPcTemplates.value = await getChannelTpl(true, modelId?.value)
}
const fetchContentPcTemplates = async () => {
  contentPcTemplates.value = await getChannelTpl(true, contentModelId?.value)
}
const fetchChannelH5Templates = async () => {
  channelH5Templates.value = await getChannelTpl(false, modelId?.value)
}
const fetchContentH5Templates = async () => {
  contentH5Templates.value = await getChannelTpl(false, contentModelId?.value)
}
const fetchProcessDefinitions = async () => {
  //category 字典定义的值不能更改
  processDefinitions.value = await getModelSimpleListApi({
    category: 'content'
  })
}
watch(visible, async () => {
  if (visible.value) {
    await fetchChannelModelList()
    await fetchContentModelList()
    if(modelId.value==null){
      modelId.value =   parent.value?.modelId ?? channelModelList.value[0]?.id
    }
    contentModelId.value = parent.value?.contentModelId ?? contentModelList.value[0]?.id
    await fetchChannelPcTemplates()
    await fetchContentPcTemplates()
    await fetchChannelList()
    await fetchChannelH5Templates()
    await fetchContentH5Templates()
    await fetchProcessDefinitions()
  }
})
const initCustoms = (customs: any) => {
  fields.value.forEach((field: any) => {
    customs[field.code] = field.defaultValue
  })
  return customs
}
</script>

<template>
  <!--TODO 待调整 disable-edit 没有权限不能编辑--->
  <dialog-form
    v-model:values="values"
    :name="t('cms.menu.channel')"
    :query-func="ChannelApi.getChannelApi"
    :create-func="ChannelApi.createChannelApi"
    :update-func="ChannelApi.updateChannelApi"
    :delete-func="ChannelApi.deleteChannelApi"
    :bean-id="channelId"
    :focus="focus"
    :init-values="
      (bean: any): any => ({
        parentId: bean?.parentId ?? parent?.id,
        modelId: bean?.modelId ?? parent?.modelId ?? channelModelList[0]?.id,
        contentModelId: bean?.contentModelId ?? parent?.contentModelId ?? contentModelList[0]?.id,
        tplPc: bean?.tplPc ?? parent?.tplPc ?? channelPcTemplates[0],
        tplMobile: bean?.tplMobile ?? parent?.tplMobile ?? channelH5Templates[0],
        contentTplPc: bean?.contentTplPc ?? parent?.contentTplPc ?? contentPcTemplates[0],
        contentTplMobile:
          bean?.contentTplMobile ?? parent?.contentTplMobile ?? contentH5Templates[0],
        pageSize: 20,
        sort: bean?.sort ?? parent?.sort ?? 10,
        listPage: bean?.listPage ?? parent?.listPage ?? true,
        listStatus: bean?.listStatus ?? parent?.listStatus ?? true,
        commentStatus: bean?.commentStatus ?? parent?.commentStatus ?? false,
        contributeStatus: bean?.contributeStatus ?? parent?.contributeStatus ?? false,
        searchStatus: bean?.searchStatus ?? parent?.searchStatus ?? true,
        customs: initCustoms({})
      })
    "
    :to-values="(bean) => ({ ...bean })"
    perms="channel"
    :model-value="modelValue"
    :disable-edit="() => false"
    label-width="120px"
    large
    @update:model-value="(event) => $emit('update:modelValue', event)"
    @finished="finished"
    @bean-change="
      (bean) => {
        modelId = bean?.modelId ?? parent?.modelId ?? contentModelList[0]?.id
        fetchChannelList()
      }
    "
  >
    <template #default="{ isEdit }">
      <el-row>
        <el-col :span="18">
          <el-row>
            <el-col :span="mainFields['name'].double ? 12 : 24">
              <el-form-item
                prop="name"
                :label="mainFields['name'].name ?? t('cms.channel.name')"
                :rules="{ required: true, message: () => t('common.required') }"
              >
                <el-input ref="focus" v-model="values.name" maxlength="50" />
              </el-form-item>
            </el-col>
            <el-col :span="mainFields['path'].double ? 12 : 24">
              <el-form-item
                prop="path"
                :rules="[
                  { required: true, message: () => t('common.required') },
                  { pattern: /^[\w-]*$/, message: () => t('cms.channel.error.path') }
                ]"
              >
                <template #label
                  ><label-tip
                    :label="mainFields['path'].name ?? t('cms.channel.path.label')"
                    message="cms.channel.path"
                    help
                /></template>
                <el-input v-model="values.path" maxlength="50" />
              </el-form-item>
            </el-col>
            <el-col
              v-if="mainFields['outLinkUrl'].show"
              :span="mainFields['outLinkUrl'].double ? 12 : 24"
            >
              <el-form-item
                prop="outLinkUrl"
                :rules="
                  mainFields['outLinkUrl'].required
                    ? [
                        { required: true, message: () => t('common.required') },
                        {
                          pattern: /^(http|\/).*$/,
                          message: () => t('cms.channel.error.outLinkUrl')
                        }
                      ]
                    : { pattern: /^(http|\/).*$/, message: () => t('cms.channel.error.outLinkUrl') }
                "
              >
                <template #label
                  ><label-tip
                    :label="mainFields['outLinkUrl'].name ?? t('cms.channel.outLinkUrl')"
                    message="channel.outLinkUrl"
                    help
                /></template>
                <el-input v-model="values.outLinkUrl" maxlength="255">
                  <template #append>
                    <el-checkbox v-model="values.linkTarget">
                      {{ t('cms.channel.linkTarget') }}</el-checkbox
                    >
                  </template>
                </el-input>
              </el-form-item>
            </el-col>

            <el-col
              v-if="mainFields['seoTitle'].show"
              :span="mainFields['seoTitle'].double ? 12 : 24"
            >
              <el-form-item
                prop="seoTitle"
                :label="mainFields['seoTitle'].name ?? t('cms.channel.seoTitle')"
                :rules="
                  mainFields['seoTitle'].required
                    ? { required: true, message: () => t('common.required') }
                    : undefined
                "
              >
                <el-input v-model="values.seoTitle" maxlength="150" />
              </el-form-item>
            </el-col>
            <el-col
              v-if="mainFields['seoKeyword'].show"
              :span="mainFields['seoKeyword'].double ? 12 : 24"
            >
              <el-form-item
                prop="seoKeyword"
                :label="mainFields['seoKeyword'].name ?? t('cms.channel.seoKeyword')"
                :rules="
                  mainFields['seoKeyword'].required
                    ? { required: true, message: () => t('common.required') }
                    : undefined
                "
              >
                <el-input v-model="values.seoKeyword" maxlength="150" />
              </el-form-item>
            </el-col>
            <el-col
              v-if="mainFields['seoDescription'].show"
              :span="mainFields['seoDescription'].double ? 12 : 24"
            >
              <el-form-item
                prop="seoDescription"
                :label="mainFields['seoDescription'].name ?? t('cms.channel.seoDescription')"
                :rules="
                  mainFields['seoDescription'].required
                    ? { required: true, message: () => t('common.required') }
                    : undefined
                "
              >
                <el-input v-model="values.seoDescription" maxlength="1000" />
              </el-form-item>
            </el-col>
            <el-col v-if="mainFields['model'].show" :span="mainFields['model'].double ? 12 : 24">
              <el-form-item
                prop="modelId"
                :label="mainFields['model'].name ?? t('cms.channel.model')"
                :rules="{ required: true, message: () => t('common.required') }"
              >
                <el-select
                  v-model="values.modelId"
                  class="w-full"
                  @change="
                    (value) => {
                      modelId = value
                      if (!isEdit) {
                        $nextTick().then(() => {
                          initCustoms(values.mainFields)
                        })
                      }
                    }
                  "
                >
                  <el-option
                    v-for="item in channelModelList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col
              v-if="mainFields['contentModel'].show"
              :span="mainFields['contentModel'].double ? 12 : 24"
            >
              <el-form-item
                prop="contentModelId"
                :label="mainFields['contentModel'].name ?? t('cms.channel.contentModel')"
                :rules="{ required: true, message: () => t('common.required') }"
              >
                <el-select v-model="values.contentModelId" class="w-full">
                  <el-option
                    v-for="item in contentModelList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-if="mainFields['tplPc'].show" :span="mainFields['tplPc'].double ? 12 : 24">
              <el-form-item
                prop="tplPc"
                :label="mainFields['tplPc'].name ?? t('cms.channel.tplPc')"
                :rules="
                  mainFields['tplPc'].required
                    ? { required: true, message: () => t('common.required') }
                    : undefined
                "
              >
                <el-select v-model="values.tplPc" class="w-full">
                  <el-option
                    v-for="item in channelPcTemplates"
                    :key="item"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col
              v-if="mainFields['tplMobile'].show"
              :span="mainFields['tplMobile'].double ? 12 : 24"
            >
              <el-form-item
                prop="tplMobile"
                :label="mainFields['tplMobile'].name ?? t('cms.channel.tplMobile')"
                :rules="
                  mainFields['tplMobile'].required
                    ? { required: true, message: () => t('common.required') }
                    : undefined
                "
              >
                <el-select v-model="values.tplMobile" class="w-full">
                  <el-option
                    v-for="item in channelH5Templates"
                    :key="item"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col
              v-if="mainFields['contentTplPc'].show"
              :span="mainFields['contentTplPc'].double ? 12 : 24"
            >
              <el-form-item
                prop="contentTplPc"
                :label="mainFields['contentTplPc'].name ?? t('cms.channel.contentTplPc')"
                :rules="
                  mainFields['contentTplPc'].required
                    ? { required: true, message: () => t('common.required') }
                    : undefined
                "
              >
                <el-select v-model="values.contentTplPc" class="w-full">
                  <el-option
                    v-for="item in contentPcTemplates"
                    :key="item"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col
              v-if="mainFields['contentTplMobile'].show"
              :span="mainFields['contentTplMobile'].double ? 12 : 24"
            >
              <el-form-item
                prop="contentTplMobile"
                :label="mainFields['contentTplMobile'].name ?? t('cms.channel.contentTplMobile')"
                :rules="
                  mainFields['contentTplMobile'].required
                    ? { required: true, message: () => t('common.required') }
                    : undefined
                "
              >
                <el-select v-model="values.contentTplMobile" class="w-full">
                  <el-option
                    v-for="item in contentH5Templates"
                    :key="item"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col
              v-if="mainFields['commentStatus'].show"
              :span="mainFields['commentStatus'].double ? 12 : 24"
            >
              <el-form-item
                prop="commentStatus"
                :label="mainFields['commentStatus'].name ?? t('cms.channel.commentStatus')"
                :rules="
                  mainFields['commentStatus'].required
                    ? { required: true, message: () => t('common.required') }
                    : undefined
                "
              >
                <el-switch v-model="values.commentStatus" />
              </el-form-item>
            </el-col>
            <el-col
              v-if="mainFields['contributeStatus'].show"
              :span="mainFields['contributeStatus'].double ? 12 : 24"
            >
              <el-form-item
                prop="contributeStatus"
                :label="mainFields['contributeStatus'].name ?? t('cms.channel.contributeStatus')"
                :rules="
                  mainFields['contributeStatus'].required
                    ? { required: true, message: () => t('common.required') }
                    : undefined
                "
              >
                <el-switch v-model="values.contributeStatus" />
              </el-form-item>
            </el-col>
            <el-col
              v-if="mainFields['searchStatus'].show"
              :span="mainFields['searchStatus'].double ? 12 : 24"
            >
              <el-form-item
                prop="searchStatus"
                :label="mainFields['searchStatus'].name ?? t('cms.channel.searchStatus')"
                :rules="
                  mainFields['searchStatus'].required
                    ? { required: true, message: () => t('common.required') }
                    : undefined
                "
              >
                <el-switch v-model="values.searchStatus" />
              </el-form-item>
            </el-col>
            <el-col
              v-if="mainFields['listImage'].show"
              :span="mainFields['listImage'].double ? 12 : 24"
            >
              <el-form-item
                prop="listImage"
                :label="mainFields['listImage'].name ?? t('cms.channel.image')"
                :rules="
                  mainFields['listImage'].required
                    ? { required: true, message: () => t('common.required') }
                    : undefined
                "
              >
                <image-upload
                  v-model="values.listImage"
                  :height="mainFields['listImage'].imageHeight"
                  :width="mainFields['listImage'].imageWidth"
                  :mode="mainFields['listImage'].imageMode"
                />
              </el-form-item>
            </el-col>
            <template v-for="field in fields" :key="field.code">
              <el-col :span="field.double ? 12 : 24">
                <el-form-item
                  :prop="`customs.${field.code}`"
                  :rules="
                    field.required
                      ? { required: true, message: () => t('common.required') }
                      : undefined
                  "
                >
                  <template #label><label-tip :label="field.name" /></template>
                  <field-item
                    v-model="values.customs[field.code]"
                    v-model:model-key="values.customs[field.code + '_cus']"
                    :field="field"
                  />
                </el-form-item>
              </el-col>
            </template>
            <el-col v-if="mainFields['txt'].show" :span="mainFields['txt'].double ? 12 : 24">
              <el-form-item
                prop="text"
                :label="mainFields['txt'].name ?? t('cms.channel.txt')"
                :rules="
                  mainFields['txt'].required
                    ? { required: true, message: () => t('common.required') }
                    : undefined
                "
              >
               <UEditor  v-model="values.txt" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="6" >
          <el-tabs type="border-card" class="ml-5">
            <el-tab-pane :label="t('cms.channel.tab.setting')">
              <el-form-item
                prop="parentId"
                :label="rightFields['parent'].name ?? t('cms.channel.parent')"
              >
                <el-tree-select
                  v-model="values.parentId"
                  :data="parentChannelList"
                  node-key="id"
                  :props="{ label: 'name', disabled: 'disabled' }"
                  :render-after-expand="false"
                  check-strictly
                  clearable
                  class="w-full"
                />
              </el-form-item>
              <el-form-item
                prop="processDefinitionId"
                :label="
                  rightFields['processDefinitionId'].name ?? t('cms.channel.processDefinitionId')
                "
                :rules="
                  rightFields['processDefinitionId'].required
                    ? { required: true, message: () => t('common.required') }
                    : undefined
                "
              >
                <el-select v-model="values.processDefinitionId" clearable class="w-full">
                  <el-option
                    v-for="item in processDefinitions"
                    :key="item.processDefinitionId"
                    :label="item.name"
                    :value="item.processDefinitionId"
                  />
                </el-select>
              </el-form-item>
              <el-form-item
                prop="listStatus"
                :rules="
                  rightFields['listStatus'].required
                    ? { required: true, message: () => t('common.required') }
                    : undefined
                "
              >
                <template #label
                  ><label-tip
                    :label="rightFields['listStatus'].name ?? t('cms.channel.listStatus.label')"
                    message="cms.channel.listStatus"
                    help
                /></template>
                <el-switch v-model="values.listStatus" />
              </el-form-item>
              <el-form-item
                prop="listPage"
                :rules="
                  rightFields['listPage'].required
                    ? { required: true, message: () => t('common.required') }
                    : undefined
                "
              >
                <template #label
                  ><label-tip
                    :label="rightFields['listPage'].name ?? t('cms.channel.listPage.label')"
                    message="cms.channel.listPage"
                    help
                /></template>
                <el-switch v-model="values.listPage" />
              </el-form-item>
              <el-form-item
                prop="pageSize"
                :label="rightFields['pageSize'].name ?? t('cms.channel.pageSize')"
                :rules="{ required: true, message: () => t('common.required') }"
              >
                <el-input-number v-model="values.pageSize" :min="1" :max="200" />
              </el-form-item>
              <el-form-item
                prop="sort"
                :label="rightFields['sort'].name ?? t('cms.channel.sort')"
                :rules="{ required: true, message: () => t('common.required') }"
              >
                <el-input-number v-model="values.sort" :min="1" :max="200" />
              </el-form-item>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </template>
  </dialog-form>
</template>

<style lang="scss" scoped>
.label-top {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }

  :deep(.el-form-item__label) {
    width: 100% !important;
    margin-bottom: 4px;
  }
}
</style>
